package com.hefan.oms.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.exception.IllegalOperationException;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.util.MapUtils;
import com.hefan.live.itf.LiveRoomService;
import com.hefan.notify.itf.ImChatroomService;
import com.hefan.oms.bean.RebalanceVo;
import com.hefan.oms.itf.AnchorTicketMonthService;
import com.hefan.oms.itf.CurrencyExchangeService;
import com.hefan.oms.itf.LiveReBalanceService;
import com.hefan.oms.itf.MessageService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.UserIdentityService;
import com.hefan.user.itf.WebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/8.
 *
 * @descrition 直播间、俱乐部用户扣费consume
 */

@Component
public class RebalanceListener implements GLLMessageListener {

    @Resource
    ImChatroomService imChatroomService;
    @Resource
    AnchorTicketMonthService anchorTicketMonthService;
    @Resource
    CurrencyExchangeService currencyExchangeService;
    @Resource
    LiveRoomService liveRoomService;
    @Resource
    UserIdentityService userIdentityService;
    @Resource
    WebUserService webUserService;
    @Resource
    JedisService jedisService;

    @Resource
    MessageService privateMessageService;
    @Resource
    MessageService falsePrivateMessageService;
    @Resource
    LiveReBalanceService liveReBalanceService;
    @Resource
    LiveReBalanceService falseLiveReBalanceService;

    private Logger logger = LoggerFactory.getLogger(RebalanceListener.class);



    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFANTV_OMS;
    }

    /**
     * 直播间和俱乐部扣费的consume
     *
     * @throws
     * @description
     * @author wangchao
     * @create 2016/11/2 11:18
     */
    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFANTV_OMS_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {return TopicRegistryTest.HEFANTV_OMS_TEST;}
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        logger.info(" oms  RebalanceListener topic={},message={},tag={}", message.getTopic(), new String(message.getBody()), message.getTag());
        try {
            //解析参数
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (CollectionUtils.isEmpty(map) || !map.containsKey("rebalanceVo")) {
                logger.error("扣费失败，参数信息为空{}", new String(message.getBody()));
                return Action.CommitMessage;
            }
            String rebalanceStr = MapUtils.getStrValue(map, "rebalanceVo", "");
            RebalanceVo rebalanceVo = JSON.parseObject(rebalanceStr, RebalanceVo.class);
            logger.debug("开始查询送礼人信息,重新获取账户余额");
            WebUser webUser = webUserService.getWebUserInfoByUserId(rebalanceVo.getFromId());
            WebUser toUser = webUserService.getWebUserInfoByUserId(rebalanceVo.getToId());

            if (webUser == null || toUser == null) {
                logger.error("送礼人/收礼人信息不存在 FromUserId:{},toUserId={}", rebalanceVo.getFromId(),rebalanceVo.getToId());
                return Action.CommitMessage;
            }
            if (webUser.getUserType() == GlobalConstants.USER_TYPE_FLASE) {
                rebalanceVo.setIsFalse(GlobalConstants.FALSE_FANPIAO);
            } else {
                rebalanceVo.setIsFalse(GlobalConstants.REAL_FANPIAO);
            }
            logger.info("送礼人信息：{}", JSONObject.toJSONString(webUser));
            rebalanceVo.setNickName(webUser.getNickName());
            //处理账户：更新账户名细收入、支出
            liveReBalanceService.dealPresentDetail(rebalanceVo,webUser);
        } catch (Exception e) {
            logger.error("RebalanceListener 扣费异常{}", e);
            e.printStackTrace();
            if (e instanceof IllegalOperationException) {
               return Action.CommitMessage;
            }
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }



}
